package com.itjin.health.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.model.PutObjectRequest;
import com.itjin.health.service.CommonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.UUID;

@Slf4j
@Service
public class CommonServiceImpl implements CommonService {
    @Resource
    private OSS ossClient;

    @Value("${alibaba.cloud.oss.bucket-name}")
    private String bucketName;

    @Value("${alibaba.cloud.oss.endpoint}")
    private String endpoint;

    @Override
    public String uploadFile(MultipartFile file) throws Exception {
        try {
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
            String fileName = "health/" + UUID.randomUUID().toString().replaceAll("-", "") + suffix;

            // 创建PutObjectRequest对象
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, file.getInputStream());

            // 上传文件
            ossClient.putObject(putObjectRequest);

            // 生成文件访问路径
            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new RuntimeException("文件上传失败: " + e.getMessage());
        }
    }
}
